
//
//  PlaceListViewController.m
//  RoadLine
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 RedFireNoodles. All rights reserved.
//

#import "PlaceListViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "PlaceModel.h"
#import "UIImageView+WebCache.h"
#import "PlaceDetailViewController.h"
#import "PlaceCell.h"
#import "MJRefresh.h"
#import "Constants.h"
#import "ViewController.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

// 地点一览
@interface PlaceListViewController ()

// 全部
@property(nonatomic, retain)NSMutableArray *allArray;
// 景点
@property(nonatomic, retain)NSMutableArray *sightsArray;
// 住宿
@property(nonatomic, retain)NSMutableArray *hotelArray;
// 餐厅
@property(nonatomic, retain)NSMutableArray *restaurantArray;
// 娱乐
@property(nonatomic, retain)NSMutableArray *experienceArray;
// 购物
@property(nonatomic, retain)NSMutableArray *mallArray;
// 分类seg
@property(nonatomic, retain)UISegmentedControl *seg;
// 显示地点信息一览
@property(nonatomic, retain)UITableView *contentTblView;

//@property(nonatomic, retain)UIActivityIndicatorView *activity;
// ［全部］页数(刷新,加载用)
@property(nonatomic, assign)NSInteger allPageIndex;
// ［景点］页数(刷新,加载用)
@property(nonatomic, assign)NSInteger sightsPageIndex;
// ［住宿］页数(刷新,加载用)
@property(nonatomic, assign)NSInteger hotelPageIndex;
// ［餐厅］页数(刷新,加载用)
@property(nonatomic, assign)NSInteger restaurantPageIndex;
// ［娱乐］页数(刷新,加载用)
@property(nonatomic, assign)NSInteger experiPageIndex;
// ［购物］页数(刷新,加载用)
@property(nonatomic, assign)NSInteger mallPageIndex;

@end

@implementation PlaceListViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.locationDic = [NSMutableDictionary dictionary];
        self.allArray = [NSMutableArray array];
        self.sightsArray = [NSMutableArray array];
        self.hotelArray = [NSMutableArray array];
        self.restaurantArray = [NSMutableArray array];
        self.experienceArray = [NSMutableArray array];
        self.mallArray = [NSMutableArray array];
//        self.activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 改变uinavigationBar 的title颜色
    UILabel *titleLabelPrice = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    titleLabelPrice.font = [UIFont boldSystemFontOfSize:18];
    titleLabelPrice.textColor = [UIColor whiteColor];
    titleLabelPrice.backgroundColor = [UIColor clearColor];
    titleLabelPrice.text = @"      列表";
    self.navigationItem.titleView = titleLabelPrice;

    [titleLabelPrice autorelease];
    
    self.seg = [[UISegmentedControl alloc] initWithItems:@[kAllSegName, kSightsSegName, kHotelSegName, kRestaurantSegName, kExperienceSegName, kMallSegName]];
    self.seg.frame = CGRectMake(10, 10, WIDTH - 20, 30);
    self.seg.tintColor = [UIColor colorWithRed:246/255.0 green:85/255.0 blue:91/255.0 alpha:1];
    [self.seg addTarget:self action:@selector(showSegView:) forControlEvents:UIControlEventValueChanged];
    self.contentTblView = [[UITableView alloc] initWithFrame:CGRectMake(10, 50, WIDTH - 20, HEIGHT - 70 - 60) style:UITableViewStylePlain];
    self.view.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
    self.contentTblView.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
    self.contentTblView.dataSource = self;
    self.contentTblView.delegate = self;
    self.contentTblView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    [self.contentTblView addSubview:self.activity];
    [self.view addSubview:self.contentTblView];
    [self.view addSubview:self.seg];
    [self parseDataWithType:kAll startIndex:@"0"];
    self.seg.selectedSegmentIndex = 0;
    
    [_contentTblView release];
    [_seg release];
    
    self.allPageIndex = 0;
    self.sightsPageIndex = 0;
    self.hotelPageIndex = 0;
    self.restaurantPageIndex = 0;
    self.mallPageIndex = 0;
    
    if ([Singleton shareSingleton].isNight) {
        [[Singleton shareSingleton] loadNightModeInfoFormDisk];
    }
    
    [self.contentTblView addLegendFooterWithRefreshingBlock:^{
        // 全部
        if (self.seg.selectedSegmentIndex == 0) {
            [self parseDataWithType:kAll startIndex:[NSString stringWithFormat:@"%ld", self.allPageIndex]];
            // 景点
        } else if (self.seg.selectedSegmentIndex == 1) {
            [self parseDataWithType:kSights startIndex:[NSString stringWithFormat:@"%ld", self.sightsPageIndex]];
            // 住宿
        } else if (self.seg.selectedSegmentIndex == 2) {
            [self parseDataWithType:kHotel startIndex:[NSString stringWithFormat:@"%ld", self.hotelPageIndex]];
            // 餐厅
        } else if (self.seg.selectedSegmentIndex == 3) {
            [self parseDataWithType:kRestaurant startIndex:[NSString stringWithFormat:@"%ld", self.restaurantPageIndex]];
            // 娱乐
        } else if (self.seg.selectedSegmentIndex == 4) {
            [self parseDataWithType:kExperience startIndex:[NSString stringWithFormat:@"%ld", self.experiPageIndex]];
            // 购物
        } else if (self.seg.selectedSegmentIndex == 5) {
            [self parseDataWithType:kMall startIndex:[NSString stringWithFormat:@"%ld", self.mallPageIndex]];
        }

    }];
    [self.contentTblView.footer beginRefreshing];

}
// 解析数据
- (void)parseDataWithType:(NSString *)strType startIndex:(NSString *)startIndex{
    // 多线程
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(mainQueue, ^{
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        // 拼接请求
        NSString *strURL = [NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@/pois/%@/?sort=default&start=%@&latitude=%@&longitude=%@", self.type, self.placeId, strType, startIndex,self.locationDic[@"lat"], self.locationDic[@"lng"]];
        [manager GET:strURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSArray *array = responseObject[@"items"];
            for (NSMutableDictionary *placeDic in array) {
                PlaceModel *place = [[PlaceModel alloc] init];
                [place setValuesForKeysWithDictionary:placeDic];
                if ([strType isEqualToString:kAll]) {
                    [self.allArray addObject:place];
                } else if ([strType isEqualToString:kSights]) {
                    [self.sightsArray addObject:place];
                } else if ([strType isEqualToString:kHotel]) {
                    [self.hotelArray addObject:place];
                } else if ([strType isEqualToString:kRestaurant]) {
                    [self.restaurantArray addObject:place];
                } else if ([strType isEqualToString:kExperience]) {
                    [self.experienceArray addObject:place];
                } else if ([strType isEqualToString:kMall]) {
                    [self.mallArray addObject:place];
                }
                [place release];
            }
//            [self.activity stopAnimating];
            [self.contentTblView reloadData];
            [self.contentTblView.footer endRefreshing];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self.contentTblView.footer endRefreshing];
        }];
    });
}
// 返回cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = 0;
    // 全部
    if (self.seg.selectedSegmentIndex == 0) {
        count = [self.allArray count];
    // 景点
    } else if (self.seg.selectedSegmentIndex == 1) {
        count = [self.sightsArray count];
    // 住宿
    } else if (self.seg.selectedSegmentIndex == 2) {
        count = [self.hotelArray count];
    // 餐厅
    } else if (self.seg.selectedSegmentIndex == 3) {
        count = [self.restaurantArray count];
    // 娱乐
    } else if (self.seg.selectedSegmentIndex == 4) {
        count = [self.experienceArray count];
    // 购物
    } else if (self.seg.selectedSegmentIndex == 5) {
        count = [self.mallArray count];
    }
    return count;
}
// 根据选择的seg铺设cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"placeListCell";
    PlaceCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[PlaceCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
    }
    if ([Singleton shareSingleton].isNight) {
        [[Singleton shareSingleton] loadNightModeInfoFormDisk];
    }
    PlaceModel *place = nil;
    // 如果选择的是［全部］并且［全部］数组里有值
    if (self.seg.selectedSegmentIndex == 0 && self.allArray.count != 0) {
        place = [self.allArray objectAtIndex:indexPath.row];
        self.allPageIndex += 1;
    // 景点
    } else if (self.seg.selectedSegmentIndex == 1 && self.sightsArray.count != 0) {
        place = [self.sightsArray objectAtIndex:indexPath.row];
        self.sightsPageIndex++;
    // 住宿
    } else if (self.seg.selectedSegmentIndex == 2 && self.hotelArray.count != 0) {
        place = [self.hotelArray objectAtIndex:indexPath.row];
        self.hotelPageIndex++;
    // 餐厅
    } else if (self.seg.selectedSegmentIndex == 3 && self.restaurantArray.count != 0) {
        place = [self.restaurantArray objectAtIndex:indexPath.row];
        self.restaurantPageIndex++;
    // 娱乐
    } else if (self.seg.selectedSegmentIndex == 4 && self.experienceArray.count != 0) {
        place = [self.experienceArray objectAtIndex:indexPath.row];
        self.experiPageIndex++;
    // 购物
    } else if (self.seg.selectedSegmentIndex == 5 && self.mallArray.count != 0) {
        place = [self.mallArray objectAtIndex:indexPath.row];
        self.mallPageIndex++;
    }
    cell.nameLbl.text = place.name;
    [cell.destImgView sd_setImageWithURL:[NSURL URLWithString:place.cover_s]];
    cell.visited_countLbl.text = [NSString stringWithFormat:@"%ld 去过", place.visited_count];
    cell.wish_to_goLbl.text = [NSString stringWithFormat:@"%ld 喜欢", place.wish_to_go_count];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
// 选seg之后切换  如果以前解析过数据  就直接读数组里的数据
- (void)showSegView:(id)sender {
    [self.self.contentTblView setContentOffset:CGPointZero animated:NO];
    if (self.seg.selectedSegmentIndex == 0) {
        if (self.allArray.count == 0) {
//            self.activity.center = CGPointMake(self.view.center.x, self.view.center.y - 64);
//            [self.activity startAnimating];
            [self parseDataWithType:@"all" startIndex:[NSString stringWithFormat:@"%ld", self.allPageIndex]];
        } else {
            [self.contentTblView reloadData];
        }
    } else if (self.seg.selectedSegmentIndex == 1) {
        if (self.sightsArray.count == 0) {
//            self.activity.center = CGPointMake(self.view.center.x, self.view.center.y - 64);
//            [self.activity startAnimating];
            [self parseDataWithType:@"sights" startIndex:[NSString stringWithFormat:@"%ld", self.sightsPageIndex]];
        } else {
            [self.contentTblView reloadData];
        }
    } else if (self.seg.selectedSegmentIndex == 2) {
        if (self.hotelArray.count == 0) {
//            self.activity.center = CGPointMake(self.view.center.x, self.view.center.y - 64);
//            [self.activity startAnimating];
            [self parseDataWithType:@"hotel" startIndex:[NSString stringWithFormat:@"%ld", self.sightsPageIndex]];
        } else {
            [self.contentTblView reloadData];
        }
    } else if (self.seg.selectedSegmentIndex == 3) {
        if (self.restaurantArray.count == 0) {
//            self.activity.center = CGPointMake(self.view.center.x, self.view.center.y - 64);
//            [self.activity startAnimating];
            [self parseDataWithType:@"restaurant" startIndex:[NSString stringWithFormat:@"%ld", self.restaurantPageIndex]];
        } else {
            [self.contentTblView reloadData];
        }
    } else if (self.seg.selectedSegmentIndex == 4) {
        if (self.experienceArray.count == 0) {
//            self.activity.center = CGPointMake(self.view.center.x, self.view.center.y - 64);
//            [self.activity startAnimating];
            [self parseDataWithType:@"experience" startIndex:[NSString stringWithFormat:@"%ld", self.experiPageIndex]];
        } else {
            [self.contentTblView reloadData];
        }
    } else if (self.seg.selectedSegmentIndex == 5) {
        if (self.mallArray.count == 0) {
//            self.activity.center = CGPointMake(self.view.center.x, self.view.center.y - 64);
//            [self.activity startAnimating];
            [self parseDataWithType:@"mall" startIndex:[NSString stringWithFormat:@"%ld", self.mallPageIndex]];
        } else {
            [self.contentTblView reloadData];
        }
    }
}
// 选择cell跳转
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PlaceDetailViewController *placeDtlVC = [[PlaceDetailViewController alloc] init];
    PlaceModel *place = nil;
    if (self.seg.selectedSegmentIndex == 0 && self.allArray.count != 0) {
        place = [self.allArray objectAtIndex:indexPath.row];
        // 景点
    } else if (self.seg.selectedSegmentIndex == 1 && self.sightsArray.count != 0) {
        place = [self.sightsArray objectAtIndex:indexPath.row];
        // 住宿
    } else if (self.seg.selectedSegmentIndex == 2 && self.hotelArray.count != 0) {
        place = [self.hotelArray objectAtIndex:indexPath.row];
        // 餐厅
    } else if (self.seg.selectedSegmentIndex == 3 && self.restaurantArray.count != 0) {
        place = [self.restaurantArray objectAtIndex:indexPath.row];
        // 娱乐
    } else if (self.seg.selectedSegmentIndex == 4 && self.experienceArray.count != 0) {
        place = [self.experienceArray objectAtIndex:indexPath.row];
        // 购物
    } else if (self.seg.selectedSegmentIndex == 5 && self.mallArray.count != 0) {
        place = [self.mallArray objectAtIndex:indexPath.row];
    }
    if (place != nil) {
        placeDtlVC.placeId = [NSString stringWithFormat:@"%@", place.placeId];
        placeDtlVC.type = [NSString stringWithFormat:@"%ld", place.type];
        [self.navigationController pushViewController:placeDtlVC animated:YES];
    }
    if ([Singleton shareSingleton].isNight) {
        [[Singleton shareSingleton] loadNightModeInfoFormDisk];
    }
    [placeDtlVC release];
}
// cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (void)setLightDayModel {
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:246/255.0 green:85/255.0 blue:91/255.0 alpha:1];
    self.view.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
    self.seg.tintColor = [UIColor colorWithRed:246/255.0 green:85/255.0 blue:91/255.0 alpha:1];
    self.contentTblView.footer.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
    self.contentTblView.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
}

- (void)setNightDayModel {
    
    self.view.backgroundColor = [UIColor blackColor];
    self.seg.tintColor = [UIColor colorWithRed:4/255.0 green:171/255.0 blue:165/255.0 alpha:1];
    self.contentTblView.footer.backgroundColor = [UIColor blackColor];
    self.contentTblView.backgroundColor = [UIColor blackColor];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:4/255.0 green:165/255.0 blue:171/255.0 alpha:1];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [_allArray release];
    [_sightsArray release];
    [_hotelArray release];
    [_restaurantArray release];
    [_experienceArray release];
    [_mallArray release];
    [_seg release];
    [_contentTblView release];
//    [_activity release];
    [_locationDic release];
    [super dealloc];
}

@end
